import axios, { AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import { CACHE_KEY, getAccessToken, getName } from './cache';

// function useLogout() {
//   const navigate = useNavigate();
//   function navTo(path: string) {
//     navigate(path);
//   }
//   navigate('/login');
//   return navTo;
// }
// const DOMAIN = 'http://127.0.0.1:7001/';
const DOMAIN = 'http://47.120.50.132:16065/';

// 创建 Axios 实例

const instance: AxiosInstance = axios.create({
  timeout: 5000, // 设置请求超时时间
  baseURL: DOMAIN,
});

// 请求拦截器
instance.interceptors.request.use(
  (config: InternalAxiosRequestConfig<any>) => {
    // 在发送请求之前做一些处理，例如添加请求头等，登录请求头
    const accessToken = getAccessToken();
    config.headers['Authorization'] = `Bearer ${accessToken}`;
    return Promise.resolve(config);
  },
  (error: any) => {
    // 处理请求错误
    return Promise.reject(error);
  },
);

// 响应拦截器
instance.interceptors.response.use(
  (response: AxiosResponse) => {
    console.log('😈response?.data?.data', response?.data?.msg?.name);
    if (
      response?.data?.data?.name === 'JsonWebTokenError' ||
      response?.data?.msg?.name === 'TokenExpiredError'
    ) {
      localStorage.removeItem(CACHE_KEY.ACCESS_TOKEN);
      window.location.href = '/#/user/login';
    }
    // 在接收响应数据之前做一些处理
    return response.data || response;
  },
  (error: any) => {
    // 处理响应错误
    return Promise.reject(error);
  },
);

// 封装 HTTP 请求方法
const http = {
  get: <T>(
    url: string,
    config?: Partial<InternalAxiosRequestConfig>,
  ): Promise<AxiosResponse<T>> => {
    return instance.get(url, config);
  },
  post: <S, T>(
    url: string,
    data?: S,
    config?: Partial<InternalAxiosRequestConfig>,
  ): Promise<AxiosResponse<T>> => {
    return instance.post(url, data, config);
  },
  put: <S, T>(
    url: string,
    data?: S,
    config?: Partial<InternalAxiosRequestConfig>,
  ): Promise<AxiosResponse<T>> => {
    return instance.put(url, data, config);
  },
  delete: <T>(
    url: string,
    config?: Partial<InternalAxiosRequestConfig>,
  ): Promise<AxiosResponse<T>> => {
    return instance.delete(url, config);
  },
};

export default http;
